const https = require('https');
const fs = require('fs');
const path = require('path');

// 确保目录存在
const dir = './public/static/images/heads';
if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
}

// 生成随机用户头像的URL列表 (使用ui-avatars服务)
const avatarUrls = [];
for (let i = 1; i <= 20; i++) {
    // 使用ui-avatars生成不同颜色和名称的头像
    const name = String.fromCharCode(65 + i) + String.fromCharCode(65 + (i % 26)); // 生成AA, AB, AC等
    avatarUrls.push({
        url: `https://ui-avatars.com/api/?name=${name}&size=128&background=random`,
        filename: `avatar${i}.png`
    });
}

// 下载图片的函数
function downloadImage(url, filename) {
    return new Promise((resolve, reject) => {
        const filePath = path.join(dir, filename);
        
        // 检查文件是否已存在
        if (fs.existsSync(filePath)) {
            console.log(`文件 ${filename} 已存在，跳过下载`);
            resolve();
            return;
        }
        
        const file = fs.createWriteStream(filePath);
        
        https.get(url, (response) => {
            if (response.statusCode === 200) {
                response.pipe(file);
                file.on('finish', () => {
                    file.close();
                    console.log(`下载完成: ${filename}`);
                    resolve();
                });
            } else {
                console.error(`下载失败: ${filename} - HTTP状态码: ${response.statusCode}`);
                fs.unlink(filePath, () => {}); // 删除部分下载的文件
                reject(new Error(`HTTP状态码: ${response.statusCode}`));
            }
        }).on('error', (err) => {
            fs.unlink(filePath, () => {}); // 删除部分下载的文件
            console.error(`下载错误: ${filename}`, err.message);
            reject(err);
        });
    });
}

// 批量下载所有头像
async function downloadAllAvatars() {
    console.log('开始下载用户头像图片...');
    
    for (let i = 0; i < avatarUrls.length; i++) {
        try {
            await downloadImage(avatarUrls[i].url, avatarUrls[i].filename);
            // 添加延迟避免请求过于频繁
            await new Promise(resolve => setTimeout(resolve, 300));
        } catch (error) {
            console.error(`下载 ${avatarUrls[i].filename} 时出错:`, error.message);
        }
    }
    
    console.log('所有头像下载完成!');
}

// 执行下载
downloadAllAvatars();